package com.woniuxy.handler;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.ArrayList;



import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


import com.woniuxy.pojo.Guest;
import com.woniuxy.pojo.Opinon;
import com.woniuxy.pojo.Order;
import com.woniuxy.pojo.OrderDTO;
import com.woniuxy.pojo.OrderDetailgjf;
import com.woniuxy.pojo.OrderDetaillyq;

import com.woniuxy.pojo.Room;
import com.woniuxy.pojo.Roomgjf;
import com.woniuxy.pojo.ShopCart;
import com.woniuxy.service.OrderService;
import com.woniuxy.util.DateUtil;

@Controller
@RequestMapping("/order")
public class OrderHandler {
	@Resource
	private OrderService orderservice;

		//个人订单确认页面
		@RequestMapping("/or")
		@ResponseBody
		public ModelAndView or(HttpServletRequest request) throws Exception{
			ModelAndView m=new ModelAndView("/payorder.html");
			//获取传过来房间类型ID
			String rrtid=request.getParameter("rtid");
			//获取传过来预定时间
			String otime=request.getParameter("date");
			DateUtil dateUtil=new DateUtil();
			ArrayList<java.sql.Date> lt=dateUtil.getCheckTimes(otime);
			//计算天数
			long day1=0;
			try {
				Date d1 = lt.get(0);// 转化第一个字符串为日期格式
				Date d2 =lt.get(1);// 转化第二个字符串为日期格式
				long days=(d2.getTime()-d1.getTime())/24/60/60/1000;
				day1=days+1;
			} catch (Exception e) {
				e.printStackTrace();
			}
			m.addObject("daynum", day1);
			//获取传过来入住时间
			m.addObject("starttime", lt.get(0));
			int rtid=Integer.parseInt(rrtid);
			Roomgjf rooms=orderservice.findRoomByRid(rtid);
			System.out.println(rooms+"--------------");
			m.addObject("rooms",rooms);
			//取出房间价格计算总金额
			BigDecimal rprice=rooms.getRprice();   //原价
			//获取用户折扣信息
			//获取登录账号id
			HttpSession session=request.getSession();
			int uid = (int) session.getAttribute("uid");
			m.addObject("uid",uid);
			System.out.println("uid----------------"+uid);
			//全场折扣
			float discount1=orderservice.findDidcount1();
			float discount2=orderservice.findDidcount2();
			float discount3=orderservice.findMemberInf(uid);
			float discount=discount1*discount2*discount3;
			
			BigDecimal discounts=new BigDecimal(discount);
			BigDecimal newprice=rprice.multiply(discounts);   //折后价
			newprice=newprice.setScale(2,BigDecimal.ROUND_HALF_UP);
			m.addObject("newprice",newprice);
			BigDecimal totalday = new BigDecimal(day1);   //入住天数
			
			BigDecimal totalprices=newprice.multiply(totalday);  //折后总价
			totalprices=totalprices.setScale(2,BigDecimal.ROUND_HALF_UP);
			m.addObject("totalprice",totalprices);
			
			//获取时间
			Date date=new Date();
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
			String time = df.format(date);
			String time2 = df2.format(date);
			m.addObject("time", time2);
			//生成订单号
			int random = (int)(Math.random()*8000+10000);
			String orderNumber=time+random;
			request.getSession().setAttribute("ordernumber", orderNumber);
			request.getSession().setAttribute("totalprice", totalprices);
			System.out.println("订单号"+orderNumber);
			m.addObject("orderNumber", orderNumber);
			//int uid =1;
			//遍历该用户下所有住客
			List<Guest> guest=orderservice.findAllGuest(uid);
			m.addObject("guest", guest);
			//m.setViewName("/payorder.html");
			return m;
		}
		
		
		
		//线下支付的订单生成
		@RequestMapping("/createOrder")
		@ResponseBody
		public String createOrder(HttpServletRequest request, String onumber,BigDecimal totalprice,
				BigDecimal rprice,BigDecimal newprice,String starttime,
				int daynum,String arrival,String message,int rtid,int gid,String opay) throws Exception{
			String result="订单生成失败！";
			System.out.println("原价"+rprice+"折后价"+newprice+"入住时间"+starttime+"入住天数"+daynum+"到达时间"+arrival+"备注"+message+"房间类型id"+rtid+"住客id"+gid);
			//转换时间
			Date date=new Date();
		    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		    String ostart=format.format(date);
		    java.util.Date d = null;  
		    try {  
		        d = format.parse(ostart);  
		    } catch (Exception e) {  
		        e.printStackTrace();  
		    }  
		    java.sql.Date ostarts = new java.sql.Date(d.getTime());
			
			//支付状态：默认未支付
			String  ostate="未支付";
			//获取uid
			HttpSession session=request.getSession();
			int uid = (int) session.getAttribute("uid");
			//int uid=1;
			System.out.println("-----创建订单-----"+onumber+"---"+ostart+"---"+totalprice);
			Order order=new Order();
			order.setOnumber(onumber);
			order.setOstart(ostarts);
			order.setOstate(ostate);
			order.setOpay(opay);
			order.setTotalprice(totalprice);
			order.setUid(uid);
			String result1=orderservice.createOrder(order);
			
			//查询oid
			int oid=orderservice.findOid(onumber);
			//生成订单项
			SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
			SimpleDateFormat formatter2 = new SimpleDateFormat( "yyyy-MM-dd");
			Date checkin = formatter2.parse(starttime);
			Date arrivals = formatter.parse(arrival);
			OrderDetailgjf ol=new OrderDetailgjf(rprice,newprice,checkin,checkin,daynum,arrivals,message,rtid,gid,oid);
			String result2=orderservice.createOrderList(ol);
			if(result1.contains("成功")&&result2.contains("成功")){
				result="订单生成成功！";
			}
			return result;
		}
		
		//线下团体支付的订单生成
		@RequestMapping("/createOrdertt")
		@ResponseBody
		public String createOrdertt(HttpServletRequest request,BigDecimal totalprice,String  opay) throws Exception{
			String result="订单生成成功！";
			//获取购物车
			HttpSession session=request.getSession();
			Object obj = session.getAttribute("myCart");
			Map<String,ShopCart> myCart=null;
			myCart=(Map<String, ShopCart>) obj;
			//生成订单号
			Date date=new Date();
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String time = df.format(date);
			String starttime = df2.format(date);
			int random = (int)(Math.random()*8000+10000);
			String orderNumber=time+random;   //订单号
			Date ostarts = df2.parse(starttime); 
			//团体折扣打折
			BigDecimal discount=new BigDecimal(0.8);
			totalprice=totalprice.multiply(discount);
			totalprice=totalprice.setScale(2,BigDecimal.ROUND_HALF_UP);
			request.getSession().setAttribute("ordernumber", orderNumber);
			request.getSession().setAttribute("totalprice", totalprice);
			String ostate="未支付";
			//获取uid
			int uid = (int) session.getAttribute("uid");
			//int uid=1;
			//创建订单对象
			Order order=new Order();
			order.setOnumber(orderNumber);
			order.setOstart(ostarts);
			order.setOstate(ostate);
			order.setOpay(opay);
			order.setTotalprice(totalprice);
			order.setUid(uid);
			String result1=orderservice.createOrder(order);
			System.out.println("-----创建订单-----"+orderNumber+"---"+ostarts+"---"+totalprice);   
			//查询oid
			int oid=orderservice.findOid(orderNumber);
			//取出购物车中的所有对象
			Iterator<Map.Entry<String, ShopCart>> it = myCart.entrySet().iterator();
			while (it.hasNext()) {
			   Map.Entry<String, ShopCart> entry = it.next();
			   String s=entry.getKey();
			   ShopCart good=myCart.get(s);
			   System.out.println("购物车中对象"+good);
			   //oldprice,totalprice,checkin,checkout,daynum,rtid,oid
			   BigDecimal oldprice=good.getPrice();
			   Date checkin=good.getStartdate();
			   Date checkout=good.getEnddate();
			   int daynum=(int) good.getDays();
			   int rtid=good.getRtid();
			   OrderDetailgjf ol=new OrderDetailgjf(oldprice,oldprice,checkin,checkout,daynum,checkin,"",rtid,0,oid);
			   String result2=orderservice.createOrderList(ol);
			   if(result2.contains("失败")||result1.contains("失败")){
				   result="订单生成失败！";
			   }
			}
			if(result.contains("成功")){
				myCart.clear();
			}
			return result;
		}
		
	
	//订单遍历
	@RequestMapping("/all")
	public ModelAndView allOrders(HttpServletRequest req){
		ModelAndView modelAndView = new ModelAndView();
		ArrayList<OrderDTO> dto = new ArrayList<>();
		int uid = (int) req.getSession().getAttribute("uid");
		ArrayList<Order> orders = orderservice.all(uid);
		for(int i = 0; i < orders.size(); i++){
			ArrayList<OrderDetaillyq> details = orderservice.findByOid(orders.get(i).getOid());
			dto.add(new OrderDTO(orders.get(i), details));
		}
		modelAndView.addObject("orderdto", dto);
		modelAndView.setViewName("/orderlist.html");
		return modelAndView;
	}
	
	@RequestMapping("/opinion")
	public ModelAndView opinion(int odid, String rtname,String checkin){
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("odid",odid);
		modelAndView.addObject("rtname",rtname);
		modelAndView.addObject("checkin",checkin);
		modelAndView.setViewName("/opinion.html");
		return modelAndView;
	}
	
	@RequestMapping("/giveOpinion")
	@ResponseBody
	public String giveOpinion(int odid,Float grade,String opinion){
		String result="评价失败";
		int i = orderservice.saveOpinion(odid,grade,opinion);
		String state = "已评价";
		int j = orderservice.updateState(odid,state);
		if(i>0 && j>0){
			result="评价成功！";
		}
		return result;
	}
	
	@RequestMapping("/allOpinion")
	public ModelAndView allOpinion(){
		ModelAndView modelAndView = new ModelAndView();
		ArrayList<Opinon> opinions1 = new ArrayList<>();
		ArrayList<Opinon> opinions2 = new ArrayList<>();
		ArrayList<Opinon> opinions3 = new ArrayList<>();
		ArrayList<Opinon> opinions4 = new ArrayList<>();
		opinions1 = orderservice.allOpinion();
		opinions2 = orderservice.allOpinion2();
		opinions3 = orderservice.allOpinion3();
		opinions4 = orderservice.allOpinion4();
		modelAndView.addObject("opinions1",opinions1);
		modelAndView.addObject("opinions2",opinions2);
		modelAndView.addObject("opinions3",opinions3);
		modelAndView.addObject("opinions4",opinions4);
		modelAndView.setViewName("/opinionlist.html");
		
		return modelAndView;
	}

}
